package com.itasura.guava.FunctionalProgramming;

import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

/**
 * @author sailor wang
 * @date 2018/10/19 下午3:40
 * @description
 */
@Slf4j
public class SupplierTest {

    //Supplier wrapped对象只初始化一次
    @Test
    public void memoizeTest() throws Exception {

        Supplier<Integer> memoize = Suppliers.memoize(new Supplier<Integer>() {
            @Override
            public Integer get() {
                log.info("init supplier wrapped object");
                return 1;
            }
        });
        log.info("first get -> {}", memoize.get());
        log.info("second get -> {}", memoize.get());
    }

    //可以使用memoizeWithExpiration函数创建过期设置的Supplier对象，时间过期，get对象会重新初始化对象
    @Test
    public void memoizeWithExpirationTest() throws Exception {
        Supplier<Integer> memoize = Suppliers.memoizeWithExpiration(new Supplier<Integer>() {
            @Override
            public Integer get() {
                System.out.println("init supplier wrapped object");
                return 1;
            }
        }, 5, TimeUnit.SECONDS);

        System.out.println(memoize.get());
        Thread.sleep(6000);
        System.out.println(memoize.get());
    }
}